import { readBody } from 'h3';
import { ArticleModel } from '~/server/models/article.model';
import { CategoryModel } from '~/server/models/category.model';

// 创建文章
export default defineEventHandler(async (event): Promise<any> => {
	try {
		const body = await readBody(event);
		const { cover, title, content, categoryId, isTop } = body;

		if (!cover || !title || !content || !categoryId) {
			return { code: 0, message: '封面、标题、内容和分类ID不能为空' };
		}

		// 校验分类是否存在
		const category = await CategoryModel.findById(categoryId);
		if (!category) {
			return { code: 0, message: '分类不存在' };
		}

		// 校验标题是否存在
		const exist = await ArticleModel.findOne({ title });
		if (exist) {
			return { code: 0, message: '文章标题已存在' };
		}

		await ArticleModel.create({ cover, title, content, categoryId, isTop });
		return { code: 1, message: '创建成功' };
	} catch (error: any) {
		return { code: 0, message: error.message };
	}
});
